﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Web.DbHelper;
using System.IO;

namespace KnowledgeCommunity.Web.Controllers
{
    public class DocumentController : Controller
    {
        DocumentHelper myDocumentHelper = new DocumentHelper();
        AccessoryHelper myAccessoryHelper = new AccessoryHelper();
        CommentHelper myCommentHelper = new CommentHelper();
        CatalogHelper myCatalogHelper = new CatalogHelper();
        UserAccountHelper myUserAccountHelper = new UserAccountHelper();
        //
        // GET: /Document/

        public ActionResult Index()
        {
           // var model = myDocumentHelper.FindByState(1);
            var model = myDocumentHelper.FindAll();
            ViewData["DocumentList"] = model;
            return View();
        }

        public ActionResult Items(int type) 
        {
            var model = myDocumentHelper.FindByDocSort(type);
            ViewData["DocumentList"] = model;
            return View();
        }

        [Authorize(Roles="admin,editor")]
        public ActionResult List()
        {
            KnowledgeCommunity.Web.Models.Page Model = new Page();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Document> datesource = GetDataSource();//要分页的数据源
            Model.DocumentList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.DocumentList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Document> GetDataSource()
        {
            var Document = myDocumentHelper.FindAll();
            List<Document> model = new List<Document>();
            foreach (var item in Document)
            {
                model.Add(item);
            }
            return model;
        }
        [Authorize(Roles = "admin,editor")]
        public ActionResult PageIndex(Models.Page Model)
        {

            //分页数据源。自己写逻辑获取。

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Document> datesource = GetDataSource();//要分页的数据源
            Model.DocumentList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("List", Model);
            }
            //return View(Model);
        }

        [HttpPost]
        public ActionResult Search()
        {
            string title = Request.Form["s_title"];
            string cont = Request.Form["s_cont"];
            DateTime start, end;
            start = Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-12-31");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }
            var apps = myDocumentHelper.SearchByKeyAndTime(title, cont, start, end);
            return View(apps);
        }

        [HttpPost]
        public ActionResult DoSearch()
        {
            string title = Request.Form["_key"];
            ViewData["appList"] = myDocumentHelper.SearchByKey(title);
            return View();
        }

        public ActionResult Details(int id)
        {
            var model = myDocumentHelper.FindById(id);
            //model.ClickNum++;
            //DoUpdateModel(model);

            var accessaries = myAccessoryHelper.FindByShapeCodeAndType(model.ShapeCode, 5);
            var comments = myCommentHelper.FindByShapeCodeAndType(model.ShapeCode, "B");
            var calalogs = myCatalogHelper.FindByBelongTo("b");
            var hotKonewledges = myDocumentHelper.FindHotDocument(8);


            //ViewData["DocumentDetails"] = model;
            ViewData["_Accessaries"] = accessaries;
            ViewData["_Comments"] = comments;
            ViewData["_Calalogs"] = calalogs;
            ViewData["_Hots"] = hotKonewledges;

            //var users = myUserAccountHelper.FindTheRankingUser();

            //var kusers = (from a in users orderby a.KonwledgeCount descending select a).Take(10);
            //var cusers = (from a in users orderby a.CommentCount descending select a).Take(10);
            //var husers = (from a in users orderby a.CommidityCount descending select a).Take(10);

            //ViewData["K_Users"] = kusers;
            //ViewData["C_Users"] = cusers;
            //ViewData["H_Users"] = husers;

            return View(model);
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult Create(Document model)
        {
            string path = null;
            string fileOldName = null;
            string extension = null;
            string url = null;

            foreach (string image in Request.Files)
            {
                if (!HasFiles.HasFile(Request.Files[image]))
                    continue;

                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"UpLoad\Documents";
                path = HasFolders.HasFolder(createPath);

                //获得文件扩展名
                fileOldName = Path.GetFileName(Request.Files[image].FileName);
                extension = Path.GetExtension(fileOldName);//扩展名 ".xxx"

                string miniType = Request.Files[image].ContentType.ToLower();

                Stream fileStream = Request.Files[image].InputStream;

                //文件重命名
                string fileNewName = RandomNumber.RandomNumberToName() + extension;

                Request.Files[image].SaveAs(Path.Combine(path, fileNewName));

                path = path + "\\" + fileNewName;
                url = "~\\UpLoad\\Documents\\" + fileNewName;

            }
            model.LoadUrl = url;
            model.ShapeCode = "D" + RandomNumber.GenerateRandomNumber();
            model.DelPath = path;
            model.AddTime = DateTime.Now;
            model.EditTime = DateTime.Now;
            model.Contributor = HttpContext.User.Identity.Name;
            model.State = 0;
            model.DocumentSort =Convert.ToInt32(Request.Form["DocSort"]);
            model.FirstClass = Convert.ToInt32(Request.Form["DocSort"]);
            model.SecondClass = Convert.ToInt32(Request.Form["DocSort"]);
            model.ThreeClass = Convert.ToInt32(Request.Form["DocSort"]);
            model.IsPublic = Convert.ToInt32(Request.Form["Ispublic"]);

            bool n = myDocumentHelper.Create(model);
            if (n)
            {
                if (HttpContext.User.IsInRole("editor") || HttpContext.User.IsInRole("admin"))
                {
                    return RedirectToAction("List", "Document");
                }
                else
                {
                    return RedirectToAction("MyDocument", "Zone");
                }
            }
            else
            {
                //回滚操作！
                System.IO.File.Delete(path);
                return RedirectToAction("Error", "Notice", new { type = 1 });
            }
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            var _Document = myDocumentHelper.FindById(id);
            return View(_Document);
        }

        [ValidateInput(false)]
        [Authorize]
        [HttpPost]
        public ActionResult Edit(Document model)
        {
            string path = "";
            string fileOldName = "";
            string extension = "";
            string url = "";

            foreach (string image in Request.Files)
            {
                if (!HasFiles.HasFile(Request.Files[image]))
                    continue;

                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"UpLoad\Documents";
                path = HasFolders.HasFolder(createPath);

                //获得文件扩展名
                fileOldName = Path.GetFileName(Request.Files[image].FileName);
                extension = Path.GetExtension(fileOldName);//扩展名 ".xxx"

                string miniType = Request.Files[image].ContentType.ToLower();

                Stream fileStream = Request.Files[image].InputStream;

                //文件重命名
                string fileNewName = RandomNumber.RandomNumberToName() + extension;

                Request.Files[image].SaveAs(Path.Combine(path, fileNewName));

                path = path + "\\" + fileNewName;
                url = "~\\UpLoad\\Documents\\" + fileNewName;

            }
            string delpath = model.DelPath;
            if (url != "" && path != "")
            {
                model.LoadUrl = url;
                model.DelPath = path;
                System.IO.File.Delete(delpath);
            }
            model.EditTime = DateTime.Now;
            if (Request.Form["DocSort"] != "0")
            {
                model.FirstClass = Convert.ToInt32(Request.Form["DocSort"]);
            }
            if (Request.Form["Ispublic"] != "0")
            {
                model.IsPublic = Convert.ToInt32(Request.Form["Ispublic"]);
            }
            DoUpdateModel(model);
            return RedirectToAction("Details", new { id = model.Id });
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            var _Document = myDocumentHelper.FindById(id);
            return View(_Document);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            bool n = myDocumentHelper.Delete(id);
            if (n)
            {
                if (HttpContext.User.IsInRole("editor") || HttpContext.User.IsInRole("admin"))
                {
                    return RedirectToAction("List", "Document");
                }
                else
                {
                    return RedirectToAction("Document", "Zone");
                }
            }
            else
                return RedirectToAction("Error", "Notice", new { type = 2 });
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Approve(int id) 
        {
            var model = myDocumentHelper.FindById(id);
            model.State = 1;
            DoUpdateModel(model);
            return RedirectToAction("Waiting", "Zone");
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Cancel(int id)
        {
            var model = myDocumentHelper.FindById(id);
            model.State = 2;
            DoUpdateModel(model);
            return RedirectToAction("Waiting", "Zone");
        }

        [Authorize]
        [HttpPost]
        public ActionResult CommentCreate()
        {
            string _id = Request.Form["Id"];
            string code = Request.Form["ShapeCode"];
            string cont = Request.Form["message"];
            int Id = 0;
            var model = new Comment();
            if (_id != "" && code != "")
            {
                if (cont != "")
                {
                    Id = Convert.ToInt32(_id);
                    model.Content = cont;
                    model.UserName = HttpContext.User.Identity.Name;
                    model.AddTime = DateTime.Now;
                    model.ShapeCode = code;
                    model.BelongTo = "B";
                    model.State = 1;
                    myCommentHelper.Create(model);
                    return RedirectToAction("Details", new { id = Id });
                }
                else
                {
                    return RedirectToAction("Details", new { id = Id });
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        CKCDB mydb = new CKCDB();

        private void DoUpdateModel(Document model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var app = mydb.Documents.Find(model.Id);
                    UpdateModel(app);
                    mydb.SaveChanges();
                }
                catch (Exception ex)
                {
                    string message = "Create in table<Documents>" + ex.ToString();
                    WriteLog.WriteSysLog(message);
                }
            }
            
        }

    }
}
